package com.sketch.commom.utils;

import java.util.Map;
import java.util.concurrent.*;

public class TimeoutHandlerUtil {
    private static final long TIMEOUT = 10_000; // 超时时间，单位为毫秒
    private ScheduledExecutorService executorService;
    private Map<String, ScheduledFuture<?>> timeoutTasks;

    public TimeoutHandlerUtil() {
        executorService = Executors.newScheduledThreadPool(1);
        timeoutTasks = new ConcurrentHashMap<>();
    }

    public void startTimeoutTask(String id) {
        ScheduledFuture<?> timeoutTask = executorService.schedule(
                () -> {
                    // 处理超时逻辑
                    handleTimeoutLogic(id);
                },
                TIMEOUT,
                TimeUnit.MILLISECONDS
        );
        timeoutTasks.put(id, timeoutTask);
    }

    public void cancelTimeoutTask(String id) {
        ScheduledFuture<?> timeoutTask = timeoutTasks.remove(id);
        if (timeoutTask != null) {
            timeoutTask.cancel(true);
        }
    }

    private void handleTimeoutLogic(String id) {
        // 在此方法中处理超时的业务逻辑
        System.out.println("超时处理逻辑，ID: " + id);
    }
}